import { Injectable, ComponentRef } from '@angular/core';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';

import { PopupOptions } from './popup.interface';
import { PopupComponent } from './popup.component';

export class PopupBuilder {

  private popupRef: ComponentRef<PopupComponent>;

  private overlayRef: OverlayRef;

  constructor(
    private overlay: Overlay,
    options: PopupOptions
  ) {
    this.createPopup();
    this.changeProps(options);
    setTimeout(() => {
      this.popupRef.instance.open();
      this.popupRef.instance.popupClose.subscribe(() => setTimeout(() => this.destroyModal(), 500));
    }, 50);
  }

  getInstance(): PopupComponent {
    return this.popupRef && this.popupRef.instance;
  }

  destroyModal(): void {
    if (this.popupRef) {
      this.overlayRef.dispose();
      this.popupRef = null;
    }
  }

  private changeProps(options: PopupOptions): void {
    if (this.popupRef) {
      Object.assign(this.popupRef.instance, options);
    }
  }

  private createPopup(): void {
    this.overlayRef = this.overlay.create();
    this.popupRef = this.overlayRef.attach(new ComponentPortal(PopupComponent));
  }

}

@Injectable()
export class PopupService {

  constructor(
    private overlay: Overlay,
  ) { }

  create<T>(options: PopupOptions<T>): PopupComponent<T> {
    return new PopupBuilder(this.overlay, options).getInstance();
  }
}
